<!--员工管理-->
<template>
  <div class="staff_management_container">
    <div class="search_box">
      <!-- <el-button type="primary" class="fl" @click="showPopup">新增</el-button> -->
      <div v-if="powerList.add.show == 1" class="btn btn_add" @click="showPopup('ruleForm')">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">新建员工</span>
      </div>
      <!-- <div v-if="powerList.export.show == 1" class="btn btn_add">
        <i class="el-icon-plus"></i>
        <span class="btn_txt">批量导入</span>
      </div> -->
      <div class="fr" >
        <el-form :model="searchForm" :inline="true" class="searchForm"  >
          <el-form-item size="small" style="width:150px;">
            <el-select v-model="searchForm.schoolId" clearable placeholder="校区">
              <el-option v-for="(item,key) in schoolList" :key="key" :label="item.schoolName" :value="item.schoolId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item size="small" style="width:100px;">
            <el-select v-model="searchForm.entryType" clearable placeholder="入职类型">
              <el-option key="1" value="1" label="全职"></el-option>
              <el-option key="2" value="2" label="兼职"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item size="small" style="width:100px;">
            <el-select v-model="searchForm.positionType" clearable placeholder="状态">
              <el-option key="1" value="1" label="在职"></el-option>
              <el-option key="2" value="2" label="离职"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item size="small" style="width: 220px; margin-right: 0;">
            <el-input placeholder="输入姓名/工号/手机号" size="small" v-model="searchForm.searchValues" @keyup.enter.native="searchData(searchValue)">
              <div slot="append" class="btn_search" @click="searchData(searchValue)">查询</div>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="clear"></div>
    </div>
    
    <div class="table_box">
      <adminTable :tableHead="tableHead" :tableData="tableData"></adminTable>
      <el-pagination
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.curPage"
        :page-sizes="[10, 20, 50]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.totalRows">
      </el-pagination>
    </div>

    <transition name="el-fade-in-linear">
      <div class="popup-container" v-show="popupState.showStatus">
        <div class="popup">
          <i class="el-icon-error icon_close" @click="popupState.showStatus = false"></i>
          <div class="title">{{popupState.popupName}}</div>

          <div class="content">
            <el-form :model="formData" ref="ruleForm" label-width="90px" :inline="true" :rules="rules" label-position="left"
               class="form">
              <div style="overflow:hidden">
                
                <el-form-item  size="small" class=""   style="margin-bottom: 20px;">
                  <el-checkbox v-model="isLogin">创建登录账号</el-checkbox>
                </el-form-item>
                <div class="clear"></div>

                <el-form-item label="登录账号 : " v-if="isLogin"  size="small" prop="accountName" class="">
                  <el-input v-model="formData.accountName" :disabled="formData.isUpdate == 0" autocomplete="off" placeholder="输入登录账号"></el-input>
                </el-form-item>
                
                <el-form-item label="员工姓名 : " prop="employeesName" size="small" class="">
                  <el-input  v-model="formData.employeesName"  autocomplete="off" placeholder="输入员工姓名"></el-input>
                </el-form-item>
                
                <el-form-item label="入职类型 : " prop="entryType" size="small" class="">
                  <el-select v-model="formData.entryType" placeholder="选择类型">
                    <el-option label="全职" value="1"></el-option>
                    <el-option label="兼职" value="2"></el-option>
                  </el-select>
                </el-form-item>
                
                <el-form-item label="入职日期 : " prop="entryTime" size="small" class="">
                  <el-date-picker
                    autocomplete="off"
                    v-model="formData.entryTime"
                    type="date"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>

                <el-form-item label="密码 : " v-if="popupState.popupName == '新增员工' && isLogin" prop="accountPassword" size="small" class="">
                  <el-input v-model="formData.accountPassword" type="password" autocomplete="off" placeholder="输入密码"></el-input>
                </el-form-item>
                
                <el-form-item label="工号 : " v-if="popupState.popupName == '编辑员工'"   size="small" class="not_must">
                  <el-input  v-model="formData.workNo" disabled autocomplete="off" placeholder="输入工号"></el-input>
                </el-form-item>

                <el-form-item label="电话 : " prop="phone" size="small" class="">
                  <el-input  v-model="formData.phone" maxlength=11 autocomplete="off" placeholder="输入电话"></el-input>
                </el-form-item>
                
                
                
                <el-form-item label="性别 : " prop="sex" size="small" class="">
                  <el-select v-model="formData.sex" placeholder="选择性别">
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="2"></el-option>
                  </el-select>
                </el-form-item>

                
                <el-form-item label="职级 : " prop="rankCode" size="small" class="">
                  <el-select v-model="formData.rankCode" placeholder="选择职级" @change="tbJobLevelChange">
                    <el-option v-for="(item, index) in tbJobLevelList" :key="index" :label="item.dicLabel" :value="item.dicCode"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="昵称 : " prop="nickName" size="small" class=" ">
                  <el-input  v-model="formData.nickName" autocomplete="off" placeholder="输入昵称"></el-input>
                </el-form-item>

                <div class="clear"></div>
                
                <div class="school_list">
                  <div class="school_item" v-for="(item, index) in formData.bmEmployeesDto" :key="index">
                    <el-form-item label="校区 : " :rules="rules.schoolId"  :prop="'bmEmployeesDto.'+ index +'.schoolId'" size="small" >
                      <el-select @change="(e) => changeSchool(e, index)" v-model="item.schoolId" placeholder="选择校区">
                        <el-option v-for="(item, index) in schoolList" :key="index" :label="item.schoolName" :value="item.schoolId"></el-option>
                      </el-select>
                    </el-form-item>

                    <el-form-item label="角色 : " :rules="rules.roleId" :prop="'bmEmployeesDto.'+ index +'.roleId'" size="small" class="">
                      <el-select v-model="item.roleId" placeholder="选择角色">
                        <el-option v-for="(item, index) in roleList" :key="index" :label="item.roleName" :value="item.roleId"></el-option>
                      </el-select>
                    </el-form-item>

                    <el-form-item label="职位 : " :rules="rules.positionCode" :prop="'bmEmployeesDto.'+ index +'.positionCode'" size="small" class="">
                      <el-select v-model="item.positionCode" placeholder="选择职位" @change="(e) => tbJobNameChange(e, index)">
                        <el-option v-for="(item, index) in tbJobNameList" :key="index" :label="item.dicLabel" :value="item.dicCode"></el-option>
                      </el-select>
                    </el-form-item>

                    <div class="icon_box">
                      <span @click="deleteSchool(index)" class="el-icon el-icon-remove-outline"></span>
                      <span @click="addSchool" class="el-icon el-icon-circle-plus-outline" style="margin-left: 10px"></span>
                    </div>
                  </div>
                </div>
              </div>

            </el-form>

            <div class="btn_box">
              <div class="btn btn_add" v-if="popupState.popupName == '新增员工'" @click="submitAdd('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>

              <div class="btn btn_add" v-if="popupState.popupName == '编辑员工'" @click="submitEdit('ruleForm')">
                <span class="btn_txt">保存</span>
              </div>
            </div>

          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<style>
.staff_management_container .popup .school_list .school_item .el-form-item--small.el-form-item  {
  margin-bottom: 0;
  margin: 15px 0;
}
.staff_management_container .popup .school_list .school_item .el-form-item--small.el-form-item label {
  width: 60px !important;
}

.staff_management_container .popup .el-input--small {
  width: 100%;
}
.staff_management_container .popup .el-form-item--mini.el-form-item, 
.staff_management_container .popup .el-form-item--small.el-form-item {
  margin-right: 20px;
  width: 30.5%;
  margin-bottom: 25px;
}

/* .staff_management_container .el-form-item__label {
  float: left;
} */
.staff_management_container .popup .el-form-item__content {
  width: calc(100% - 90px)
}
</style>

<style scoped>
.staff_management_container .btn_add i {
  margin-right: 5px;
  margin-left: 10px;
}

.icon_box{
  display: inline-block;
  line-height: 62px;
}
.el-icon {
  cursor: pointer;
  color: #77A4FF;
}
.school_list .school_item {
  background: #F0F2F5;
  padding: 0 0 0 20px !important;
  box-sizing: border-box;
  margin-bottom: 10px;;
}

.school_list .school_item 

.btn_box {
  margin-top: 20px;
}
.popup .content {
  padding-top: 30px;
}
</style>

<script>
import adminTable from '@/components/assembly/adminTable'
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("staffManagement");
export default {
  name: 'staffManagement',
  data() {
    return {
      powerList: {
        add: {
          show: 0,
          menuId: ''
        },
        export: {
          show: 0,
          menuId: '',
        }
      },
      accountId: '',
      isLogin: false,
      popupState: {
        showStatus: false,
        popupName: '新增员工',
      },
      page: {
        curPage: 0,
        pageSize: 0,
        totalRows: 0,
      },
      searchForm: {
        schoolId: '',
        entryType: '',
        positionType: '',
        searchValues: '',
      },
      formData: {
        accountName: '',
        employeesName: '',
        entryType: '',
        entryTime: '',
        accountPassword: '',
        workNo: '',
        phone: '',
        roleId: '',
        sex: '',
        positionCode: '',
        rankCode: '',
        nickName: '',
        schoolId: '',
        isLogin: false,
        positionName: '',
        rankName: '',
        bmEmployeesDto: [
          {
            schoolId: '',
            roleId: '',
            positionCode: '',
            positionName: '',
          }
        ]
      },
      searchValue: '',

      tableHead: {
        operation_width: '200px',
        setFunction: [
          {
            showState: "2",
            hideKey: "positionType",
            fun: this.tableEdit,
            name: "编辑"
          },
          {
            showState: "2",
            hideKey: "positionType",
            fun: this.tableDelete,
            name: "删除"
          },
          {
            showState: "2",
            hideKey: "positionType",
            fun: this.resetPassword,
            name: "重置密码"
          },
        ],
        data: [
          {
            name: '工号',
            key: 'workNo',
            align: 'center',
          },
          {
            name: "姓名",
            key: "employeesName",
            align: "center",
            width: '80px',
          },
          {
            name: "昵称",
            key: "nickName",
            align: "center",
            width: '80px',
          },
          {
            name: "手机号码",
            key: "phone",
            align: "center"
          },
          {
            name: "所属校区",
            key: "schoolName",
            align: "center"
          },
          {
            name: "职位",
            key: "positionName",
            align: "center",
            width: 80,
          },
          {
            name: "角色",
            key: "roleName",
            align: "center"
          },
          {
            name: "数据权限",
            key: "dataPermissions",
            align: "center"
          },
          {
            name: "就职状态",
            key: "positionType",
            align: "center",
            width: 80,
            filter: {
              1: '在职',
              2: '离职',
            }
          },
        ]
      },
      tableData: [],

      tbJobNameList: [],
      tbJobLevelList: [],
      schoolList: [],
      powerSchoolList: [],
      roleList: [],

      deleteIds: [],

      rules: {
        accountName: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
        ],
        employeesName: [
          { required: true, message: '请输入员工姓名', trigger: 'blur' },
        ],
        entryType: [
          { required: false, message: '请选择入职类型', trigger: 'change' },
        ],
        entryTime: [
          { required: true, message: '请选择入职时间', trigger: 'change' },
        ],
        accountPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: false, message: '请输入手机号', trigger: 'blur' },
          {pattern: /^1[34578]\d{9}$/, message: '手机号格式错误'}
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'change' },
        ],
        sex: [
          { required: false, message: '请选择性别', trigger: 'change' },
        ],
        positionCode: [
          { required: true, message: '请选择职位', trigger: 'change' },
        ],
        rankCode: [
          { required: false, message: '请选择职级', trigger: 'change' },
        ],
        nickName: [
          { required: false, message: '请输入昵称', trigger: 'blur' },
        ],
        schoolId: [
          { required: false, message: '请选择校区', trigger: 'change' },
        ],
      }
    }
  },
  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    this.queryAllSchool();
    
    this.initSelect();
  },
  
  
  methods: {
    ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),

    initData(searchForm) {
      // console.log(searchValue)
      let searchValue = searchForm || this.searchForm || '';
      let data = {}
      Object.assign(data, searchValue);
      data.curPage = this.page.curPage;
      data.pageSize = this.page.pageSize;
      data.accountId = this.jwtAuth.accountId;
      data.menuId = this.$route.name;

      if(data.schoolId == '') {
        let arr = []
        this.schoolList.forEach(item => {
          arr.push(item.schoolId)
        });
        data.schoolId = arr;
        // data.schoolId = '';
      }else{
        data.schoolId = []
        data.schoolId.push(this.searchForm.schoolId)
      }

      this.post({
        API: 'selectBmEmployeesPageList',
        data: data
      }).then(res => {
        this.tableData = res.data;
        
        res.buttons.menuList[0].children.forEach(item => {
          if(item.label == '新建员工') {
            this.powerList.add.show = 1
            this.powerList.add.menuId = item.menuId
          }
          if(item.label == '批量导入') {
            this.powerList.export.show = 1
            this.powerList.export.menuId = item.menuId
          }
          console.log(this.powerList)
        })

        this.page = res.page;
      }).catch(err => {
        this.$message.error(err);
      })
    },

    initSelect() {
      this.formGet({    // 职位
        API: 'queryByDicKey',
        data: {
          dicKey: 'tbJobName'
        }
      }).then(res => {
        this.tbJobNameList = res;
      })
      
      this.formGet({    // 职级
        API: 'queryByDicKey',
        data: {
          dicKey: 'tbJobLevel'
        }
      }).then(res => {
        this.tbJobLevelList = res;
      })

      this.post({    // 全部角色
        API: 'queryAllRole',
        data: {}
      }).then(res => {
        this.roleList = res;
      })
    },

    queryAllSchool(btnId) {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      
      this.post({    // 校区
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || this.$route.name,
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        if(btnId) {
          this.powerSchoolList = res
        }else{
          this.schoolList = res
          this.initData();
        }
        // this.schoolList = res;
        // this.initData();
      })
    },

    // 新增提交
    submitAdd(formName) {
      this.formData.isLogin = this.isLogin == true? '1': '0'

      let data = this.formData;

      let bool = this.voidSchoolId(data);
      console.log(bool);
      if(bool) {
        this.$message.error('不可选择两个相同校区');
        return false;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.post({
            API: 'insert',
            data: data
          }).then(res => {
            if(res == 1) {
              this.$message.success('新建成功')
              this.initData();
              this.popupState.showStatus = false;
            }
          }).catch(err => {
            this.$message.error(err);
          })
        } else {
          return false;
        }
      });

      
    },

    // 编辑提交
    submitEdit(rowData) {

      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.formData.isLogin = this.isLogin == true? '1': '0'
          let data = this.formData

          let bool = this.voidSchoolId(data);
          console.log(bool);
          if(bool) {
            this.$message.error('不可选择两个相同校区');
            return false;
          }
          
          data.accountId = this.accountId;
          // data.deleteIds = this.deleteIds;

          console.log(data);
          // return false;
          this.post({
            API: 'update',
            data: data
          }).then(res => {
            this.$message.success('修改成功');
            this.initData();
            this.popupState.showStatus = false;
          }).catch(err => {
            this.$message.error(err);
          })
        }
      });
    },

    // 验证是否有两个相同校区
    voidSchoolId(data) {
      data = data.bmEmployeesDto
      let arr = [];
      data.forEach(item => {
        arr.push(item.schoolId);
      })
      let hash = {};
      for(let i in arr) {
        if(hash[arr[i]]) {
          return true;
　　     }
        hash[arr[i]] = true;
      }
      return false;
    },

    // 表格编辑 回显
    tableEdit(rowData) {
      this.accountId = rowData.row.accountId;
      let data = {
        id: this.accountId,
      }
      this.formGet({
        API: 'selectById',
        data: data
      }).then(res => {
        this.popupState = {
          popupName: '编辑员工',
          showStatus: true,
        }
        this.$refs['ruleForm'].resetFields();
        this.formData = res;
        this.isLogin = this.formData.isLogin == 1? true: false
        // this.formData.schoolType = this.formData.schoolType.toString();
        
      }).catch(err => {
        this.$message.error(err);
      })
    },

    deleteSchool(index) {
      if(this.formData.bmEmployeesDto.length == 1) {
        return false;
      }else{
        // this.deleteIds.push(this.formData.bmEmployeesDto[index].schoolId);
        this.formData.bmEmployeesDto.splice(index, 1)
        console.log(this.formData.bmEmployeesDto[index]);
      }

    },
    addSchool() {
      let obj = {
        schoolId: '',
        roleId: '',
        positionCode: '',
      }

      this.formData.bmEmployeesDto.push(obj);
    },



    // 表格删除
    tableDelete(rowData) {
      let accountId = rowData.row.accountId;
      let data = {
        id: accountId,
      }

      this.$confirm('是否删除该员工?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formGet({
          API: 'deleteById',
          data: data
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.initData();
        }).catch(err => {
          this.$message.error(err);
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });

      
      
    },

    // 重置密码
    resetPassword(rowData) {
      let accountId = rowData.row.accountId;
      let data = {
        accountId: accountId,
      }

      this.$confirm('是否重置改员工登录密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.formGet({
          API: 'resetPassWord',
          data: data
        }).then(res => {
          this.$message({
            type: 'success',
            message: '密码重置成功!'
          });
          this.initData();
        }).catch(err => {
          this.$message.error(err);
        })
        
      }).catch(() => {

      });
    },

    showPopup(formName) {
      let btnId = this.powerList.add.menuId;
      this.queryAllSchool(btnId);

      this.popupState = {
        showStatus: true,
        popupName: '新增员工',
      },
      this.$refs[formName].resetFields();   // 初始化
      this.formData.bmEmployeesDto = [
        {
          schoolId: '',
          roleId: '',
          positionCode: '',
          positionName: '',
        }
      ]
      this.formData.entryTime = ''
      console.log(this.formData)
    },
    searchData(searchValue) {
      this.page.curPage = 1;
      this.initData(searchValue)
    },

    // 更改校区
    changeSchool(e, index) {
      console.log(e);
      let list = this.formData.bmEmployeesDto
      if(list.length > 1) {
        for(let i=0; i<list.length; i++) {
          if(list[i].schoolId == e && index !== i) {
            console.log(index)
            console.log(i)
            this.$message.error('不可选择两个相同校区');
            this.formData.bmEmployeesDto[index].schoolId = '';
            return false;
          }
        }
      }
    },
    tbJobNameChange(e, index) {
      this.tbJobNameList.forEach(item => {
        if(item.dicCode == e) {
          this.formData.positionName = item.dicLabel;
          this.formData.bmEmployeesDto[index].positionName = item.dicLabel;
        }
      })
    },
    tbJobLevelChange(e) {
      this.tbJobLevelList.forEach(item => {
        if(item.dicCode == e) {
          this.formData.rankName = item.dicLabel;
        }
      })
    },

    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.page.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.page.curPage = val;
      this.initData();
    }
    
  },
  computed: {
    ...mapState([
    ]),
    // ...mapGetters(["selectedIds"])
  },
  components: {
    adminTable,
  },
}

</script>